package com.stn.zjx.givingtreasure.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.orhanobut.logger.Logger;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.userlogin.RegisterUserActivity;
import com.stn.zjx.givingtreasure.activity.userlogin.UserPassResetActivity;
import com.stn.zjx.givingtreasure.application.StnApp;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.GoLoginEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.event.UserLoginEvent;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.QQWeixinApi;
import com.stn.zjx.givingtreasure.net.impl.BaseNetImpl;
import com.stn.zjx.givingtreasure.net.impl.QQWeixinNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxRegTool;
import com.vondear.rxtools.view.RxToast;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import cn.jpush.android.api.JPushInterface;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class UserLoginActivity extends BaseActivity implements AMapLocationListener {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.iv_avatar)
    CircleImageView ivAvatar;
    @BindView(R.id.forgetpassword_bt)
    TextView forgetpasswordBt;
    @BindView(R.id.validate_bt)
    TextView validateBt;
    @BindView(R.id.getvalidate_ll)
    LinearLayout getvalidateLl;
    @BindView(R.id.switch_bt)
    TextView switchBt;

    boolean isAccount = false;
    @BindView(R.id.pssword_ll)
    LinearLayout psswordLl;
    @BindView(R.id.login_bt)
    ButtonBgUi loginBt;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.validate_edit)
    EditText validateEdit;
    @BindView(R.id.nickname)
    TextView nickname;
     //正在发送中
    boolean isSendLoading = false;
    int seconds = 60;
    Disposable sendvalidate__disposable = null;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    EventHandler eh;

    AmapLocationService amapLocationService=null;

    private String  userProvince="";
    private String  userCity="";
    private String  userArea="";
    private  String userAddress="";
    private  String userLongitude="";
    private  String userLatitude="";
    private String userLoginip="";

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);
        ButterKnife.bind(this);
        initComponent();


    }
    @Override
    public void initComponent() {
        swtichAccount();
      //设置昵称
        nickname.setText("");
       //设置头像

        phoneEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
//                    nickname.setText("");
//                    ivAvatar.setImageResource(R.mipmap.ic_avatar);
                }else{
                    if(!TextUtils.isEmpty(phoneEdit.getText().toString().trim())){
                        getuser_profile(phoneEdit.getText().toString().trim());
                    }
                }
            }
        });
        phoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if(TextUtils.isEmpty(charSequence)){
                        loginBt.setClickable(false);
                        loginBt.setAlpha(0.5f);
                    }else{
                        loginBt.setClickable(true);
                        loginBt.setAlpha(1.0f);
                    }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        validateBt.setOnClickListener(v -> {
            if(!message_check()){
                return;
            }
            sendValidate();
            SMSSDK.getVerificationCode("86",""+phoneEdit.getText().toString().trim());
        });
       loginBt.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               if (isAccount) {
                   if(!loginCheck()){
                       return;
                   }
                   login(phoneEdit.getText().toString().trim(),passwordEdit.getText().toString().trim());

               } else {
                   //手机号直接免注册登陆
                   if(!nopass_loginCheck()){
                       return;
                   }
                   SMSSDK.submitVerificationCode("86",phoneEdit.getText().toString().trim(),
                           validateEdit.getText().toString().trim());

               }
           }
       });
        loginBt.setClickable(false);
        loginBt.setAlpha(0.5f);

        eh=new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                no_passlogin(phoneEdit.getText().toString().trim());
                            }
                        });
                        //提交验证码成功
                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast(getString(R.string.sms_send_wait));
                            }
                        });

                    }
                }else{

                    runOnUiThread(() -> {
                        String str= ((Throwable) data).getMessage();
                        try {
                            JSONObject jb = new JSONObject(str);
                         showToast(jb.getString("detail"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                    ((Throwable)data).printStackTrace();
                }
            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(eh!=null){
            SMSSDK.registerEventHandler(eh); //注册短信回调
        }
        amapLocationService=new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();

      BaseNetImpl.get_webIp("get", new StringCallback() {
          @Override
          public void onSuccess(Response<String> response) {
              try {
                  JSONObject data=new JSONObject(response.body().substring(response.body().indexOf("{"),response.body().indexOf("}")+1));
                if(data.getString("cip")!=null){
                   userLoginip=data.getString("cip");

                }
              } catch (JSONException e) {
                  e.printStackTrace();
              }


          }
      });

    }

    //发送短信验证
    public void sendValidate() {
        sendvalidate__disposable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) {
                while (isSendLoading && seconds > 0) {
                    seconds--;
                    observableEmitter.onNext(seconds);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        sendvalidate__disposable.dispose();
                        e.printStackTrace();
                    }
                }
                observableEmitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        isSendLoading = true;
                        validateBt.setTextColor(getResources().getColor(R.color.darkgray));
                        validateBt.setClickable(false);

                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void accept(Integer seconds) {
                        isSendLoading = true;
                        validateBt.setText(getString(R.string.surplus)
                                + "" + seconds + getString(R.string.seconds)
                                + getString(R.string.resend));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        sendvalidate__disposable.dispose();
                        reset_sendValidate();
                    }
                }, new Action() {
                    @Override
                    public void run() {
                        reset_sendValidate();
                    }
                });


    }

    public void swtichAccount() {
        if (isAccount) {
            isAccount = false;
            actionTitle.setText(getString(R.string.dynamic_login));
            switchBt.setText(getString(R.string.password_login));
            psswordLl.setVisibility(View.GONE);
            getvalidateLl.setVisibility(View.VISIBLE);
            YoYo.with(Techniques.SlideInLeft)
                    .duration(500)
                    .playOn(switchBt);
            YoYo.with(Techniques.FadeInLeft)
                    .duration(500)
                    .playOn(switchBt);
            validateEdit.getText().clear();
        } else {
            isAccount = true;
            actionTitle.setText(getString(R.string.password_login));
            switchBt.setText(getString(R.string.dynamic_login));
            getvalidateLl.setVisibility(View.GONE);
            psswordLl.setVisibility(View.VISIBLE);
            YoYo.with(Techniques.SlideInLeft)
                    .duration(500)
                    .playOn(switchBt);
            YoYo.with(Techniques.FadeInLeft)
                    .duration(500)
                    .playOn(switchBt);
            passwordEdit.getText().clear();
        }
    }

    @OnClick({R.id.back_bt, R.id.forgetpassword_bt, R.id.getvalidate_ll, R.id.switch_bt,
            R.id.weixin_login_bt, R.id.qq_login_bt,
    R.id.registeruser_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.forgetpassword_bt:

           RxActivityTool.skipActivity(this,UserPassResetActivity.class);
                break;
            case R.id.switch_bt:
                swtichAccount();
                break;
            case R.id.weixin_login_bt:

                wxlogin();
                break;
            case R.id.qq_login_bt:
                qqLogin();
                break;



            case R.id.registeruser_bt:
               RxActivityTool.skipActivity(this,RegisterUserActivity.class);
                break;
        }
    }

    //用户密码登陆检查
    public boolean loginCheck() {
        if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
            showToast(getString(R.string.phone_isnotempty));
            return  false;
        }
        if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {

            showToast(getString(R.string.please_isnotreal_phone));
            return false;
        }
        if (TextUtils.isEmpty(passwordEdit.getText().toString().trim())) {
            showToast(getString(R.string.password_isnotempty));
            return  false;
        }
        if(!ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())){
            showToast(getString(R.string.password_validate));
            return false;
        }
        return true;
    }

    //免密码用户登陆检查
    public boolean nopass_loginCheck() {
        if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
            showToast(getString(R.string.phone_isnotempty));
            return  false;
        }
        if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
            showToast(getString(R.string.please_isnotreal_phone));
            return false;
        }

        if (TextUtils.isEmpty(validateEdit.getText().toString().trim())) {
            showToast(getString(R.string.sms_isnotempty));
            return  false;
        }
        if(!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return false;
        }
        return true;
    }

    //短信发送验证检查
    public boolean message_check() {
        if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {

            showToast(getString(R.string.phone_isnotempty));

            return  false;
        }
        if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
            showToast(getString(R.string.please_isnotreal_phone));
            return false;
        }
        if(!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return false;
        }
        return true;
    }

    //重置发送短信按钮
    public void reset_sendValidate() {
        isSendLoading = false;
        validateBt.setText(getString(R.string.get_validate));
        validateBt.setTextColor(getResources().getColor(R.color.default_black));
        seconds = 60;
        validateBt.setClickable(true);
    }


   //用户登录
   public void login(String userPhone,String userPwd){
       if(!RxNetTool.isAvailable(this)) {
           showToast(getString(R.string.request_networkavailable));
             return;
       }
       JSONObject location=new JSONObject();
       try {
           location.put("userLoginip",userLoginip);
           location.put("userProvince",userProvince);
           location.put("userCity",userCity);
           location.put("userArea",userArea);
           location.put("userLongitude",userLongitude);
           location.put("userLatitude",userLatitude);
           location.put("userAddress",userAddress);
           UserNetImpl.user_login(userPhone,userPwd,location.toString(),"user_login",
                   new StringCallback() {
                       @Override
                       public void onStart(Request<String, ? extends Request> request) {
                           super.onStart(request);
                           showLoading();
                       }
                       @Override
                       public void onSuccess(Response<String> response) {
                           System.out.println("*************"+getLocalClassName()+":"+response.body());
                           if(response.isSuccessful()&&!isFinishing()){
                               if(response.body()==null){
                                   showToast(response.message());
                                   return;
                               }
                               Gson gson=new Gson();
                               UserProfileDomain domain=gson.fromJson(response.body(), UserProfileDomain.class);
                               switch (domain.getStatus()){
                                   case BaseApi.REQUEST_SUCCESS_CODE:
                                       loginSuccess(domain);
                                       break;
                                   default:
                                       showToast(domain.getMessage());
                                       break;
                               }
                           }else{
                               showToast(response.message());
                           }
                       }

                       @Override
                       public void onError(Response<String> response) {
                           super.onError(response);
                           showToast(getString(R.string.request_please_wait));
                       }
                       @Override
                       public void onFinish() {
                           super.onFinish();
                           if(!isFinishing()){
                               dissmissLoading();
                           }
                       }
                   });
       } catch (Exception e) {
           e.printStackTrace();
           showToast(e.getMessage());
       }

   }


    //免密码登录
    public void no_passlogin(String userPhone){
        if(!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return;
        }
        JSONObject location=new JSONObject();
        try {
            location.put("userLoginip",userLoginip);
            location.put("userProvince",userProvince);
            location.put("userCity",userCity);
            location.put("userArea",userArea);
            location.put("userLongitude",userLongitude);
            location.put("userLatitude",userLatitude);
            location.put("userAddress",userAddress);
            UserNetImpl.user_login_nopassword(userPhone,location.toString(),"user_login_nopassword",
                    new StringCallback() {
                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            super.onStart(request);
                            showLoading();
                        }
                        @Override
                        public void onSuccess(Response<String> response) {
                            if(response.isSuccessful()&&!isFinishing()){
                                if(response.body()==null){
                                    showToast(response.message());
                                    return;
                                }

                                Gson gson=new Gson();
                                UserProfileDomain domain=gson.fromJson(response.body().trim(), UserProfileDomain.class);
                                switch (domain.getStatus()){
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        loginSuccess(domain);
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                            }else{
                                showToast(response.message());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            showToast(getString(R.string.request_please_wait));
                        }
                        @Override
                        public void onFinish() {
                            super.onFinish();
                            if(!isFinishing()){
                                dissmissLoading();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }

    }


    //通过手机号，获取用户资料信息
    public void getuser_profile(String userPhone){
        if(!RxNetTool.isAvailable(this)) {
            return;
        }
        UserNetImpl.user_query_profile(userPhone,"user_query_profile",
                new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response.isSuccessful()&&!isFinishing()){
//                            if(response.body()==null){
//                                RxToast.error(getString(R.string.request_please_wait),Toast.LENGTH_SHORT);
//                                return;
//                            }
                            Logger.json(""+response.body());
                            try {
                                JSONObject data=new JSONObject(response.body());
                                switch (data.getInt(BaseApi.KEY_STATUS)){
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        JSONObject  jsondata=data.getJSONObject(BaseApi.KEY_DATA);
                                        String userAvatar=jsondata.getString("userAvatar");
                                        String userNickname=jsondata.getString( "userNickname");
                                        nickname.setText(userNickname);
                                        RequestOptions options=new RequestOptions();
                                        options.placeholder(R.mipmap.default_avatar);
                                        Glide.with(UserLoginActivity.this)
                                                .asBitmap()
                                                .load(userAvatar)
                                                .apply(options)
                                                .into(new SimpleTarget<Bitmap>() {
                                                    @Override
                                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                         if(!isFinishing()){
                                                             ivAvatar.setImageBitmap(resource);
                                                         }
                                                    }
                                                });
                                        break;
                                    default:

                                        break;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else{

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    @Override
    protected void onStop() {
        super.onStop();
        if(eh!=null){
            SMSSDK.unregisterEventHandler(eh);
        }
        if(amapLocationService!=null){
            amapLocationService.stop();
            amapLocationService.unregisterListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendvalidate__disposable != null) {
            sendvalidate__disposable.dispose();
            reset_sendValidate();
        }

    }



    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

            if (aMapLocation.getErrorCode() == 0) {
                userProvince=aMapLocation.getProvince();
                userCity=aMapLocation.getCity();
                userArea=aMapLocation.getDistrict();
                userAddress=aMapLocation.getAddress().substring(9,aMapLocation.getAddress().length());
                userLongitude=aMapLocation.getLongitude()+"";
                userLatitude=aMapLocation.getLatitude()+"";
            }
    }

    //用户在服务器手机号，密码校验正确
    private void loginSuccess(UserProfileDomain domain) {
        boolean isLogin= UserService.getInstance(getApplicationContext())
                .login(domain.getData());
        if(isLogin){
      //      showToast(domain.getMessage());
            JPushInterface.setAlias(this,domain.getData().getUserId(),""+domain.getData().getUserId());
            RefreshEvent event=new RefreshEvent();
            event.flag=RefreshEvent.LOGIN_REFRESH;
            EventBus.getDefault().post(event);
            finish();
        }else{
            showToast(getString(R.string.db_error_loginerror));
        }
    }



    @Subscribe(threadMode= ThreadMode.MAIN)
    public void onLogin(UserLoginEvent event){
        switch (event.flag){
            case UserLoginEvent.USERLOGIN_REGISTER_FINISH:
                if(!isAccount){
                    swtichAccount();
                }
                phoneEdit.setText(event.phone);
                passwordEdit.setText(event.password);
//                login(phoneEdit.getText().toString().trim(),passwordEdit.getText().toString().trim());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //QQ验证登录
            case Constants.REQUEST_LOGIN:

                Tencent.onActivityResultData(requestCode, resultCode, data, new QQLoginListener());
                break;
        }

    }

    //QQ登录监听
    public class QQLoginListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            showLoading();
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            try {
                int ret = jo.getInt("ret");
                if (ret == 0) {
                    String openid = jo.getString("openid");
                    String access_token = jo.getString("access_token");
                    String expires_in = jo.getString("expires_in");
                    StnApp.tencent.setOpenId(openid);
                    StnApp.tencent.setAccessToken(access_token, expires_in);
                    UserInfo qqInfo = new UserInfo(getApplicationContext(), StnApp.tencent.getQQToken());
                    qqInfo.getUserInfo(new QQgetUserListener(openid));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                dissmissLoading();
            }
        }

        @Override
        public void onError(UiError uiError) {
           showToast(getString(R.string.request_please_wait));
        }

        @Override
        public void onCancel() {
        }
    }

    //得到QQ用户信息
    public class QQgetUserListener implements IUiListener {
        String openid = "";

        public QQgetUserListener(String openid) {
            this.openid = openid;
        }

        @Override
        public void onComplete(Object o) {
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            String path = "";
            String nickname = "";
            String gender = "男";
            try {
                nickname = jo.getString("nickname");
                gender = jo.getString("gender");
                path = jo.getString("figureurl_qq_2");
                GoLoginEvent event=new GoLoginEvent();
                event.loginType=0;
                event.sex=gender;
                event.userAvatar=path;
                event.userNickname=nickname;
                event.id=openid;
                EventBus.getDefault()
                        .post(event);
             dissmissLoading();
            } catch (JSONException e) {
                e.printStackTrace();
                dissmissLoading();
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    }
    //QQ登录
    public void qqLogin() {
         if(!StnApp.tencent.isQQInstalled(this)){
              showToast(getString(R.string.no_install_qq));
         }
         showToast(getString(R.string.loading_open__qq));
        StnApp.tencent.login(this, "all", new QQLoginListener());
    }
    //微信登录
    public void wxlogin() {
        showToast(getString(R.string.loading_open__wexin));
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wxchat_login";
        StnApp.iwxapi.sendReq(req);//执行完毕这句话之后，会在WXEntryActivity回调
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoLoginEvent(GoLoginEvent event){

        if(!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return;
        }
        String userNickname=event.userNickname;
        String userAvatar=event.userAvatar;
        Integer userSex=0;
       if(event.sex.equals("男")){
           userSex=1;
       }else {
           userSex=2;
       }
        String id=event.id;
        Integer loginType=event.loginType;

        JSONObject location=new JSONObject();
        try {
            location.put("userLoginip",userLoginip);
            location.put("userProvince",userProvince);
            location.put("userCity",userCity);
            location.put("userArea",userArea);
            location.put("userLongitude",userLongitude);
            location.put("userLatitude",userLatitude);
            location.put("userAddress",userAddress);
            QQWeixinNetImpl.qqweixin_third_login(userNickname,
                    userAvatar,
                    userSex,
                       id,
                    loginType,
                    location.toString(),"qqweixin_third_login",
                    new StringCallback() {
                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            super.onStart(request);
                            showLoading();
                        }
                        @Override
                        public void onSuccess(Response<String> response) {
                            if(response.isSuccessful()){
                                if(response.body()==null){
                                    showToast(response.message());
                                    return;
                                }

                                Gson gson=new Gson();
                                UserProfileDomain domain=gson.fromJson(response.body().trim(), UserProfileDomain.class);
                                switch (domain.getStatus()){
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        loginSuccess(domain);
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                            }else{
                                showToast(response.message());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            showToast(getString(R.string.request_please_wait));
                        }
                        @Override
                        public void onFinish() {
                            super.onFinish();
                            if(!isFinishing()){
                                dissmissLoading();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }
    }

}
